/*
 * Copyright (C) 2021 Chinasoft International
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import router from '@system.router';
import prompt from '@system.prompt';

// 0：采用Ability调用方式; 1：Internal Ability调用方式
const ABILITY_TYPE_EXTERNAL = 0;
// 0：同步 1：异步
const ACTION_SYNC = 0;
//订阅模式
const ACTION_MESSAGE_CODE_PLUS_SUB = 1002;
//取消订阅
const ACTION_MESSAGE_CODE_PLUS_UNSUB = 1003;
const TO_SUB = 1002;

export default {
	data: {
	//       进度条数值
		message: 0,
	//       控制提示（加载中）的显示和隐藏
		isShow: false
	},
	onShow() {
		this.message = 0;
		console.log('ddcc')
	},
	/**
     *   请求开启订阅模式
     */
	subscribe: async function() {
		this.isShow = true; // 显示进度条内容
		var that = this;

		var actionData = {};
		actionData.firstNum = that.message;

		var action = {};
		action.bundleName = 'com.example.javajscommunication'; // Ability的包名称，需要与PA端匹配，区分大小写
		action.abilityName = 'com.example.javajscommunication.ServiceAbility'; // Ability名称，需要与PA端匹配，区分大小写
		action.messageCode = ACTION_MESSAGE_CODE_PLUS_SUB; // Ability操作码（操作码定义PA的业务功能，需要与PA端约定)
		action.data = actionData; // 发送到Ability的数据,数据字段名称需要与PA端约定
		action.abilityType = ABILITY_TYPE_EXTERNAL; // Ability类型，对应PA端不同的实现方式
		action.syncOption = ACTION_SYNC; // PA侧请求消息处理同步/异步选项 0：同步方式，默认方式。 1：异步方式

		await FeatureAbility.subscribeAbilityEvent(action, function (callbackData) {
			var callbackJson = JSON.parse(callbackData); // json字符串反序列化
			that.message = callbackJson.data.abilityEvent;
			if (that.message == 100) { // message 为100时进行跳转计算页面
				router.push({
					uri: "pages/calculate/calculate"
				})
				that.unsubscribe(); // 取消订阅
				that.isShow = false; // 隐藏进度条
			}
		})
	},
/*
        请求取消订阅, java端停止返回数据
     */
	unsubscribe: async function() {
		var action = {};
		action.bundleName = 'com.example.javajscommunication';
		action.abilityName = 'com.example.javajscommunication.ServiceAbility';
		action.messageCode = ACTION_MESSAGE_CODE_PLUS_UNSUB;
		action.abilityType = ABILITY_TYPE_EXTERNAL;
		action.syncOption = ACTION_SYNC;

		var result = await FeatureAbility.unsubscribeAbilityEvent(action);
		var ret = JSON.parse(result);
		if (ret.code == 0) {
			prompt.showToast({
				message: '取消下载成功'
			})
		} else {
			prompt.showToast({
				message: '取消下载失败'
			})
		}
	}
}
